# -*- coding: utf-8 -*-
"""

"""
# imports
from django.test import Client, TestCase
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.sessions.backends.db import SessionStore
from django import template

from noaccount.models import User, EmailAccount

# classes

# @link http://www.djangosnippets.org/snippets/963/
# @contributor J.Ducastel
class RequestFactory(Client):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    This class re-uses the django.test.client.Client interface, docs here:
    http://www.djangoproject.com/documentation/testing/#the-test-client

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.

    """
    def request(self, **request):
        """
        Similar to parent class, but returns the request object as soon as it
        has created it.
        """
        environ = {
            'HTTP_COOKIE': self.cookies,
            'PATH_INFO': '/',
            'QUERY_STRING': '',
            'REQUEST_METHOD': 'GET',
            'SCRIPT_NAME': '',
            'SERVER_NAME': 'testserver',
            'SERVER_PORT': 80,
            'SERVER_PROTOCOL': 'HTTP/1.1',
        }
        environ.update(self.defaults)
        environ.update(request)
        r = WSGIRequest(environ)
        r.session = SessionStore()
        return r

class BaseCase(TestCase):
    """base test case with fixtures and utility methods"""
    def setUp(self):
        self.accounts = [
            {'email': 'first@user.net', 'password': u'S3cr3et'},
            {'email': 'french@user.net', 'password': u"De l'unicode ? Où ça ? Là !"},
        ]
        # will be a list of ids
        self.users = []
        for a in self.accounts:
            user = User.objects.create()
            self.users.append(user.id)
            acc = EmailAccount.register(user, a['email'], a['password'])
        # forcing default settings
        from noaccount import settings
        settings.CLOSED_MODE = False
    
    def _request(self):
        return RequestFactory().request()
    
    def assertTemplateOrFailback(self, response, template, failback):
        """assert that response used template if exists, or failback if not"""
        if self._template_exists(template):
            self.assertTemplateUsed(response, template)
        else:
            self.assertTemplateUsed(response, failback)

    def _template_exists(self, name):
        """checks for template existence"""
        try:
            template.loader.get_template(name)
            return True
        except template.TemplateDoesNotExist:
            return False